package com.hyz.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.hyz.reggie.common.BaseContext;
import com.hyz.reggie.pojo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        String[] uris = {"/employee/login", "/employee/logout", "/backend/**", "/front/**"};
        if (check(uri, uris)) {
            filterChain.doFilter(request, response);
            return;
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("employee") != null) {
            BaseContext.setCurrentID((Long) session.getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public boolean check(String uri, String[] uris) {
        for (String s : uris) {
            if (PATH_MATCHER.match(s, uri)) {
                return true;
            }
        }
        return false;
    }
}
